/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import entities.Album;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Nordinator
 */
@Stateless
@LocalBean
public class AlbumManager {
    @PersistenceContext(unitName = "Project-MP3-Rumble-ejbPU")
    private EntityManager em;

    /**
     * 
     * @param object 
     */
    public void persist(Object object) {
        em.persist(object);
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    /**
     * 
     * @return 
     */
    public List<Album> getAllAlbums() {
        Query query = em.createNamedQuery("Album.findAll");
        return query.getResultList();
    }
    
    /**
     * Fonction de creation et de mise à jour de la base de donnée
     * @param album
     * @return
     */
    public Album update(Album album) {
        return em.merge(album);
    }
    
    /**
     * Methode d'ajout d'album dans la base de donnée
     * @param album
     * @param chanson
     * @return 
     */
    public Album ajouterAlbum(String album, String chanson){
        try{
            Query query = em.createNamedQuery("Album.findByName");
            query.setParameter("name", album);
            if(query.getResultList().isEmpty()){
                Album tmp = new Album(album);
                tmp.addSong(chanson);
                em.persist(tmp);
                return tmp;
            }else{
                Album tmp = (Album) query.getResultList().get(0);
                tmp.addSong(chanson);
                return em.merge(tmp);
            }
         }catch(Exception e){
             e.printStackTrace();
         }
        return null;
    }
    
    public void Test(){
        
    }
}
